/**
 * 本地存储管理
 */

const { CACHE_KEYS, CACHE_EXPIRY } = require('./constants')

class StorageManager {
  // 兼容静态调用 Storage.getUserInfo()
  static getUserInfo() {
    if (!StorageManager._instance) {
      StorageManager._instance = new StorageManager();
    }
    return StorageManager._instance.user.getUserInfo();
  }
  /**
   * 存储数据（带过期时间）
   */
  set(key, value, expiry = null) {
    try {
      const item = {
        value: value,
        timestamp: Date.now(),
        expiry: expiry
      }
      wx.setStorageSync(key, JSON.stringify(item))
      return true
    } catch (error) {
      console.error('Storage set error:', error)
      return false
    }
  }

  /**
   * 获取数据
   */
  get(key, defaultValue = null) {
    try {
      const itemStr = wx.getStorageSync(key)
      if (!itemStr) return defaultValue

      const item = JSON.parse(itemStr)
      
      // 检查是否过期
      if (item.expiry && Date.now() - item.timestamp > item.expiry) {
        this.remove(key)
        return defaultValue
      }

      return item.value
    } catch (error) {
      console.error('Storage get error:', error)
      return defaultValue
    }
  }

  /**
   * 移除数据
   */
  remove(key) {
    try {
      wx.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('Storage remove error:', error)
      return false
    }
  }

  /**
   * 清空所有数据
   */
  clear() {
    try {
      wx.clearStorageSync()
      return true
    } catch (error) {
      console.error('Storage clear error:', error)
      return false
    }
  }

  /**
   * 检查数据是否存在且未过期
   */
  has(key) {
    const value = this.get(key)
    return value !== null
  }

  /**
   * 获取存储使用情况
   */
  getStorageInfo() {
    return new Promise((resolve) => {
      wx.getStorageInfo({
        success: resolve,
        fail: () => resolve(null)
      })
    })
  }

  /**
   * 用户相关存储
   */
  user = {
    setToken: (token) => {
      return this.set(CACHE_KEYS.TOKEN, token, CACHE_EXPIRY.TOKEN)
    },

    getToken: () => {
      return this.get(CACHE_KEYS.TOKEN)
    },

    removeToken: () => {
      return this.remove(CACHE_KEYS.TOKEN)
    },

    setUserInfo: (userInfo) => {
      return this.set(CACHE_KEYS.USER_INFO, userInfo, CACHE_EXPIRY.USER_INFO)
    },

    getUserInfo: () => {
      return this.get(CACHE_KEYS.USER_INFO)
    },

    removeUserInfo: () => {
      return this.remove(CACHE_KEYS.USER_INFO)
    },

    clearUserData: () => {
      this.removeToken()
      this.removeUserInfo()
    }
  }

  /**
   * 位置相关存储
   */
  location = {
    setLocation: (location) => {
      return this.set(CACHE_KEYS.USER_LOCATION, location, CACHE_EXPIRY.TEMPORARY)
    },

    getLocation: () => {
      return this.get(CACHE_KEYS.USER_LOCATION)
    },

    removeLocation: () => {
      return this.remove(CACHE_KEYS.USER_LOCATION)
    }
  }

  /**
   * 搜索历史
   */
  search = {
    addHistory: (keyword) => {
      if (!keyword.trim()) return

      let history = this.getHistory()
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制数量
      if (history.length > 20) {
        history = history.slice(0, 20)
      }

      return this.set(CACHE_KEYS.SEARCH_HISTORY, history, CACHE_EXPIRY.SEARCH_HISTORY)
    },

    getHistory: () => {
      return this.get(CACHE_KEYS.SEARCH_HISTORY, [])
    },

    clearHistory: () => {
      return this.remove(CACHE_KEYS.SEARCH_HISTORY)
    },

    removeHistoryItem: (keyword) => {
      let history = this.getHistory()
      history = history.filter(item => item !== keyword)
      return this.set(CACHE_KEYS.SEARCH_HISTORY, history, CACHE_EXPIRY.SEARCH_HISTORY)
    }
  }

  /**
   * 收藏管理
   */
  favorites = {
    addFavorite: (type, id) => {
      let favorites = this.getFavorites()
      const key = `${type}_${id}`
      
      if (!favorites[type]) {
        favorites[type] = []
      }
      
      if (!favorites[type].includes(id)) {
        favorites[type].push(id)
        return this.set(CACHE_KEYS.FAVORITES, favorites)
      }
      
      return true
    },

    removeFavorite: (type, id) => {
      let favorites = this.getFavorites()
      
      if (favorites[type]) {
        favorites[type] = favorites[type].filter(item => item !== id)
        return this.set(CACHE_KEYS.FAVORITES, favorites)
      }
      
      return true
    },

    isFavorite: (type, id) => {
      const favorites = this.getFavorites()
      return favorites[type] && favorites[type].includes(id)
    },

    getFavorites: () => {
      return this.get(CACHE_KEYS.FAVORITES, {})
    },

    getFavoritesByType: (type) => {
      const favorites = this.getFavorites()
      return favorites[type] || []
    },

    clearFavorites: () => {
      return this.remove(CACHE_KEYS.FAVORITES)
    }
  }

  /**
   * 应用设置
   */
  settings = {
    setSetting: (key, value) => {
      let settings = this.getSettings()
      settings[key] = value
      return this.set(CACHE_KEYS.SETTINGS, settings)
    },

    getSetting: (key, defaultValue = null) => {
      const settings = this.getSettings()
      return settings[key] !== undefined ? settings[key] : defaultValue
    },

    getSettings: () => {
      return this.get(CACHE_KEYS.SETTINGS, {})
    },

    removeSetting: (key) => {
      let settings = this.getSettings()
      delete settings[key]
      return this.set(CACHE_KEYS.SETTINGS, settings)
    },

    clearSettings: () => {
      return this.remove(CACHE_KEYS.SETTINGS)
    }
  }

  /**
   * 临时缓存（短期）
   */
  temp = {
    set: (key, value, expiry = CACHE_EXPIRY.TEMPORARY) => {
      return this.set(`temp_${key}`, value, expiry)
    },

    get: (key, defaultValue = null) => {
      return this.get(`temp_${key}`, defaultValue)
    },

    remove: (key) => {
      return this.remove(`temp_${key}`)
    }
  }

  /**
   * 清理过期数据
   */
  cleanup() {
    try {
      const storageInfo = wx.getStorageInfoSync()
      const keys = storageInfo.keys

      keys.forEach(key => {
        try {
          const itemStr = wx.getStorageSync(key)
          if (itemStr) {
            const item = JSON.parse(itemStr)
            if (item.expiry && Date.now() - item.timestamp > item.expiry) {
              wx.removeStorageSync(key)
            }
          }
        } catch (error) {
          // 无效数据，删除
          wx.removeStorageSync(key)
        }
      })

      return true
    } catch (error) {
      console.error('Storage cleanup error:', error)
      return false
    }
  }

  /**
   * 导出数据（用于备份）
   */
  export() {
    try {
      const storageInfo = wx.getStorageInfoSync()
      const keys = storageInfo.keys
      const data = {}

      keys.forEach(key => {
        try {
          data[key] = wx.getStorageSync(key)
        } catch (error) {
          console.warn(`Failed to export ${key}:`, error)
        }
      })

      return data
    } catch (error) {
      console.error('Storage export error:', error)
      return null
    }
  }

  /**
   * 导入数据（用于恢复）
   */
  import(data) {
    try {
      Object.keys(data).forEach(key => {
        try {
          wx.setStorageSync(key, data[key])
        } catch (error) {
          console.warn(`Failed to import ${key}:`, error)
        }
      })
      return true
    } catch (error) {
      console.error('Storage import error:', error)
      return false
    }
  }
}

module.exports = new StorageManager()
